<?php

namespace App\Http\Middleware;
use App\Exceptions\MissParamException;
use App\Models\WechatConfig;
use Closure;
use Config;
use Symfony\Component\Cache\Simple\FilesystemCache;

class SetWechatConfig
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if($request->has('appid')) {
            global $appId;
            $appId = $request->get('appid');
            $config = WechatConfig::where('app_id', $appId)->first();
            if($config){
                global $wechatName;
                global $wechatId;
                $wechatId = $config->id;
                $wechatName = $config->name;
                Config::set('wechat.app_id', $config->app_id);
                Config::set('wechat.secret', $config->secret);
                Config::set('wechat.token', $config->token);
                Config::set('wechat.aes_key', $config->aes_key);

                $cache = new FilesystemCache();
                Config::set('wechat.cache', $cache);

                if($config->type == 2) {
                    //服务号
                    Config::set('wechat.oauth.only_wechat_browser', $config->oauth_only_wechat_browser);
                    Config::set('wechat.oauth.scopes', $config->oauth_scopes);
                    Config::set('wechat.oauth.callback', $config->oauth_callback);
                }
            }else{
                throw new MissParamException("微信appid({$appId})的数据不存在");
            }
        }else{
            throw new MissParamException("缺少appid参数");
        }
        $response = $next($request);
        return $response;
    }
}
